package com.audaque.springboot.foshanupload.gateway.config;

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author zgb
 * @desc spring cloud gateway 默认使用redis的RateLimter限流算法来实现。
 * @date 2023-08-01 18:32:12
 */
@Configuration
public class RateLimterConfig {
    //通过KeyResolver来指定限流的Key。
    @Bean
    public KeyResolver ipKeyResolver() {
        return new KeyResolver() {
            @Override
            public Mono<String> resolve(ServerWebExchange exchange) {
                return Mono.just(exchange.getRequest().getRemoteAddress().getHostName());
            }
        };
    }

    /**
     * 按IP来限流
     */
   /*     @Bean
        public KeyResolver ipAddrKeyResolver() {//JDK8的新特性——Lambda表达式
            return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getAddress().getHostAddress());
        }
*/
    ///**
    // * 按用户限流
    // */
    //@Bean
    //KeyResolver userKeyResolver() {
    //    return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst("user"));
    //}

    ///**
    // * 按URL限流,即以每秒内请求数按URL分组统计，超出限流的url请求都将返回429状态
    // *
    // * @return
    // */
    //@Bean
    //@Primary
    //KeyResolver apiKeyResolver() {
    //    return exchange -> Mono.just(exchange.getRequest().getPath().toString());
    //}


}
